import { useState } from 'react';
import { BookCard } from '@/components/BookCard';
import { BottomNav } from '@/components/BottomNav';
import { useAppStore, PictureBook } from '@/stores/appStore';
import { cn } from '@/utils/cn';
import { Search, Filter, Grid, List, Heart, Star, ChevronDown } from 'lucide-react';
import { useNavigate } from 'react-router-dom';

export default function BooksPage() {
  const navigate = useNavigate();
  const { books, toggleFavorite } = useAppStore();
  
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('全部');
  const [selectedAge, setSelectedAge] = useState('全部');
  const [sortBy, setSortBy] = useState<'rating' | 'readCount' | 'newest'>('rating');
  const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid');
  const [showFilters, setShowFilters] = useState(false);

  // 获取所有分类和年龄段
  const categories = ['全部', ...Array.from(new Set(books.map(book => book.category)))];
  const ageRanges = ['全部', '3-5岁', '6-8岁', '9-12岁'];

  // 过滤和排序逻辑
  const filteredBooks = books.filter(book => {
    const matchesSearch = book.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         book.author.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         book.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()));
    
    const matchesCategory = selectedCategory === '全部' || book.category === selectedCategory;
    
    const matchesAge = selectedAge === '全部' || (() => {
      const ageMatch = book.ageRange.match(/(\d+)-(\d+)岁/);
      if (!ageMatch) return true;
      const minAge = parseInt(ageMatch[1]);
      const maxAge = parseInt(ageMatch[2]);
      if (selectedAge === '3-5岁') return minAge >= 3 && maxAge <= 5;
      if (selectedAge === '6-8岁') return minAge >= 6 && maxAge <= 8;
      if (selectedAge === '9-12岁') return minAge >= 9 && maxAge <= 12;
      return true;
    })();

    return matchesSearch && matchesCategory && matchesAge;
  }).sort((a, b) => {
    switch (sortBy) {
      case 'rating':
        return b.rating - a.rating;
      case 'readCount':
        return b.readCount - a.readCount;
      case 'newest':
        return new Date(b.id).getTime() - new Date(a.id).getTime();
      default:
        return 0;
    }
  });

  const handleBookClick = (bookId: string) => {
    navigate(`/books/${bookId}`);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-primary-50 via-warm-50 to-secondary-50">
      <BottomNav />
      
      <main className={cn(
        "px-4 py-6 md:py-8",
        "pt-20 md:pt-8", // 为顶部导航留出空间
        "pb-24 md:pb-8"  // 为底部导航留出空间
      )}>
        
        {/* 页面标题 */}
        <div className="max-w-7xl mx-auto mb-8">
          <h1 className="text-3xl md:text-4xl font-bold text-gray-800 mb-2">绘本馆</h1>
          <p className="text-gray-600">发现适合孩子的优质绘本</p>
        </div>

        {/* 搜索和筛选栏 */}
        <div className="max-w-7xl mx-auto mb-8">
          <div className="bg-white rounded-2xl shadow-lg p-6">
            <div className="flex flex-col md:flex-row gap-4 mb-4">
              {/* 搜索框 */}
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="text"
                  placeholder="搜索绘本、作者或标签..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent-500 focus:border-transparent"
                />
              </div>

              {/* 筛选按钮 */}
              <button
                onClick={() => setShowFilters(!showFilters)}
                className="flex items-center px-4 py-3 bg-warm-50 hover:bg-warm-100 text-gray-700 rounded-xl transition-colors"
              >
                <Filter className="w-5 h-5 mr-2" />
                筛选
                <ChevronDown className={cn("w-4 h-4 ml-2 transition-transform", showFilters && "rotate-180")} />
              </button>

              {/* 视图模式切换 */}
              <div className="flex bg-gray-100 rounded-xl p-1">
                <button
                  onClick={() => setViewMode('grid')}
                  className={cn(
                    "p-2 rounded-lg transition-colors",
                    viewMode === 'grid' ? "bg-white text-primary-600 shadow-sm" : "text-gray-600 hover:text-gray-800"
                  )}
                >
                  <Grid className="w-5 h-5" />
                </button>
                <button
                  onClick={() => setViewMode('list')}
                  className={cn(
                    "p-2 rounded-lg transition-colors",
                    viewMode === 'list' ? "bg-white text-primary-600 shadow-sm" : "text-gray-600 hover:text-gray-800"
                  )}
                >
                  <List className="w-5 h-5" />
                </button>
              </div>
            </div>

            {/* 筛选条件 */}
            {showFilters && (
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4 pt-4 border-t border-gray-200">
                {/* 分类筛选 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">分类</label>
                  <select
                    value={selectedCategory}
                    onChange={(e) => setSelectedCategory(e.target.value)}
                    className="w-full p-2 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent-500"
                  >
                    {categories.map(category => (
                      <option key={category} value={category}>{category}</option>
                    ))}
                  </select>
                </div>

                {/* 年龄段筛选 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">年龄段</label>
                  <select
                    value={selectedAge}
                    onChange={(e) => setSelectedAge(e.target.value)}
                    className="w-full p-2 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent-500"
                  >
                    {ageRanges.map(age => (
                      <option key={age} value={age}>{age}</option>
                    ))}
                  </select>
                </div>

                {/* 排序方式 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">排序</label>
                  <select
                    value={sortBy}
                    onChange={(e) => setSortBy(e.target.value as any)}
                    className="w-full p-2 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-accent-500"
                  >
                    <option value="rating">评分最高</option>
                    <option value="readCount">阅读最多</option>
                    <option value="newest">最新上架</option>
                  </select>
                </div>

                {/* 重置按钮 */}
                <div className="flex items-end">
                  <button
                    onClick={() => {
                      setSearchTerm('');
                      setSelectedCategory('全部');
                      setSelectedAge('全部');
                      setSortBy('rating');
                    }}
                    className="w-full px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl transition-colors"
                  >
                    重置筛选
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* 结果统计 */}
        <div className="max-w-7xl mx-auto mb-6">
          <div className="flex items-center justify-between bg-white rounded-xl p-4 shadow-sm">
            <span className="text-gray-600">
              找到 <span className="font-semibold text-primary-600">{filteredBooks.length}</span> 本绘本
            </span>
            <div className="flex items-center space-x-2">
              <Star className="w-5 h-5 text-yellow-400" />
              <span className="text-sm text-gray-600">平均评分: </span>
              <span className="font-semibold text-gray-800">
                {filteredBooks.length > 0 
                  ? (filteredBooks.reduce((sum, book) => sum + book.rating, 0) / filteredBooks.length).toFixed(1)
                  : '0.0'
                }
              </span>
            </div>
          </div>
        </div>

        {/* 绘本列表 */}
        <div className="max-w-7xl mx-auto">
          {viewMode === 'grid' ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {filteredBooks.map((book) => (
                <BookCard
                  key={book.id}
                  book={book}
                  onFavorite={toggleFavorite}
                  onRead={handleBookClick}
                />
              ))}
            </div>
          ) : (
            <div className="space-y-4">
              {filteredBooks.map((book) => (
                <BookListItem
                  key={book.id}
                  book={book}
                  onFavorite={toggleFavorite}
                  onRead={handleBookClick}
                />
              ))}
            </div>
          )}
        </div>

        {/* 空状态 */}
        {filteredBooks.length === 0 && (
          <div className="max-w-7xl mx-auto text-center py-12">
            <div className="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <Search className="w-12 h-12 text-gray-400" />
            </div>
            <h3 className="text-xl font-semibold text-gray-800 mb-2">没有找到相关绘本</h3>
            <p className="text-gray-600">试试调整搜索条件或筛选选项</p>
          </div>
        )}
      </main>
    </div>
  );
}

// 列表视图组件
interface BookListItemProps {
  book: PictureBook;
  onFavorite: (bookId: string) => void;
  onRead: (bookId: string) => void;
}

function BookListItem({ book, onFavorite, onRead }: BookListItemProps) {
  return (
    <div className="bg-white rounded-2xl shadow-lg p-6 hover:shadow-xl transition-all duration-300">
      <div className="flex gap-6">
        <div className="relative flex-shrink-0">
          <img
            src={book.coverImage}
            alt={book.title}
            className="w-32 h-40 object-cover rounded-xl"
          />
          <button
            onClick={() => onFavorite(book.id)}
            className={cn(
              "absolute top-2 right-2 p-2 rounded-full transition-colors bg-white/90",
              false 
                ? "text-red-500 hover:bg-red-50" 
                : "text-gray-400 hover:bg-white hover:text-red-500"
            )}
          >
            <Heart className={cn("w-5 h-5", false && "fill-current")} />
          </button>
        </div>
        
        <div className="flex-1">
          <div className="flex items-start justify-between mb-2">
            <h3 className="text-xl font-bold text-gray-800 mb-2">{book.title}</h3>
            {book.price && (
              <span className="text-xl font-bold text-primary-600">¥{book.price}</span>
            )}
          </div>
          
          <p className="text-gray-600 mb-3">{book.author} 著</p>
          <p className="text-gray-700 mb-4 line-clamp-3">{book.description}</p>
          
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <div className="flex items-center space-x-1">
                <Star className="w-5 h-5 text-yellow-400 fill-current" />
                <span className="font-medium text-gray-700">{book.rating}</span>
              </div>
              <span className="text-sm text-gray-500">{book.readCount} 次阅读</span>
              <span className="bg-primary-100 text-primary-700 px-2 py-1 rounded-lg text-sm font-medium">
                {book.ageRange[0]}-{book.ageRange[1]}岁
              </span>
            </div>
            
            <button
              onClick={() => onRead(book.id)}
              className="px-6 py-2 bg-accent-500 hover:bg-accent-600 text-white rounded-xl font-medium transition-colors"
            >
              开始阅读
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}